const compare = (a, b) => {
  return a[0] - b[0] || a[1] - b[1] || 1;
};

// 计算区间并集个数
const calcIntervalCount = originIntervals => {
  const intervals = [],
    singles = [];

  originIntervals.forEach(interval => {
    if (Array.isArray(interval) && !isNaN(interval[0]) && !isNaN(interval[1])) {
      intervals.push(interval);
    } else if (!isNaN(interval)) {
      singles.push(interval);
    }
  });

  const sortedIntervals = intervals.sort(compare);
  let combinedIntervals = [];
  sortedIntervals.forEach(inteval => {
    const [currentStart, currentEnd] = inteval;
    if (!combinedIntervals.length) {
      combinedIntervals.push([currentStart, currentEnd]);
      return;
    }
    const [lastStart, lastEnd] = combinedIntervals[combinedIntervals.length - 1];

    if (lastStart <= currentStart && currentEnd <= lastEnd) {
      return;
    }
    if (lastStart <= currentStart && currentStart <= lastEnd && currentEnd > lastEnd) {
      combinedIntervals[combinedIntervals.length - 1][1] = currentEnd;
      return;
    }
    if (currentStart > lastEnd) {
      combinedIntervals.push([currentStart, currentEnd]);
    }
  });

  const singlesSet = new Set(singles);
  let singlesSetSize = singlesSet.size;
  singlesSet.forEach(single => {
    combinedIntervals.forEach(cidrRange => {
      if (cidrRange[0] <= single && single <= cidrRange[1]) {
        singlesSetSize--;
      }
    });
  });

  const intervalsSize = combinedIntervals.reduce((size, current) => {
    return size + current[1] - current[0] + 1;
  }, 0);

  return intervalsSize + singlesSetSize;
};

export default calcIntervalCount;
